package com.face.pass.active.utils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.face.pass.active.model.Machine;

public class DeviceUtils {

	private final static Logger LOG = LoggerFactory.getLogger(DeviceUtils.class);
	private final static String cmd = "{find_face_pay}";
	private final static byte[] buf = new byte[4096];
	private final static int port = 5656;

	public static List<String> getNetworkAddress() {
		List<String> result = new ArrayList<String>();
		Enumeration<NetworkInterface> netInterfaces;
		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip;
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> addresses = ni.getInetAddresses();
				while (addresses.hasMoreElements()) {
					ip = addresses.nextElement();
					if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1) {
						result.add(ip.getHostAddress());
					}
				}
			}
		} catch (Exception e) {

		}
		return result;
	}

	public static List<Machine> findDevices() {
		List<Machine> machines = new ArrayList<>();
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket();
			socket.setSoTimeout(1000);
			socket.setReuseAddress(true);
			List<String> addresses = getNetworkAddress();
			for(String address : addresses) {
				address =  address.substring(0, address.lastIndexOf("."))+".255";
				LOG.debug("address:"+ address);
				DatagramPacket packet = new DatagramPacket(cmd.getBytes(), cmd.getBytes().length,
						InetAddress.getByName(address), port);
				socket.send(packet);
			}
			DatagramPacket receive = new DatagramPacket(buf, buf.length);
			while (receive.getData() != null) {
				socket.receive(receive);
				String info = new String(receive.getData(), receive.getOffset(), receive.getLength(), "UTF-8");
				LOG.debug("receive: " + info);
				JSONObject machineInfo = JSON.parseObject(info);
				if(machineInfo != null) {
					final String machineId = machineInfo.getString("machineId");
					final boolean active = machineInfo.getBooleanValue("active");
					final String machineIp = machineInfo.getString("machineIp");
					Machine machine = new Machine();
					machine.setMachineId(machineId);
					machine.setMachineIp(machineIp);
					machine.setActive(active?1:0);
					if(active) {
						machine.setActiveDate(new Date());
					}
					machine.setCreateDate(new Date());
					machines.add(machine);
				}
			}
		} catch (IOException e) {
			LOG.debug("局域网内未发现设备");
		} finally {
			if (socket != null) {
				socket.close();
			}
		}
		return machines;
	}
	
	public static boolean connect(String ip) {
		
		return false;
	}

	public static void main(String[] args) {
		findDevices();
	}

}
